/*
 * Powered By fanrenqij.com
 * Since 2017 - 2017
 */

package com.fanrenqiji.modules.business.feedback.web;


import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.persistence.Page;
import com.fanrenqiji.common.utils.JSONHelper;
import com.fanrenqiji.common.utils.RegexUtils;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.modules.business.feedback.service.FeedbackService;
import com.fanrenqiji.modules.business.feedback.vo.DealVo;
import com.fanrenqiji.modules.business.feedback.vo.FeedbackVO;
import com.fanrenqiji.modules.business.feedback.vo.Media;
import com.fanrenqiji.modules.business.feedbackdetail.service.FeedbackDetailService;
import com.fanrenqiji.modules.business.feedbackdetail.vo.FeedbackDetailVO;
import com.fanrenqiji.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}/business/feedback")
public class FeedbackController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(FeedbackController.class);
    @Autowired
    private FeedbackService feedbackService;
    @Autowired
    private FeedbackDetailService feedbackDetailService;

    @ModelAttribute("feedback")
    public FeedbackVO getFeedback(@RequestParam(required = false) String id) {
        if (StringUtils.isNotEmpty(id)) {
            return feedbackService.get(id);
        } else {
            return new FeedbackVO();
        }
    }

    /**
     * 列表
     *
     * @return
     */
    @RequiresPermissions("business:feedback:view")
    @RequestMapping(value = {"list", ""})
    public String list(FeedbackVO feedback, HttpServletRequest request,
                       HttpServletResponse response, Model model) {
        Page<FeedbackVO> page = feedbackService.findFeedbackByPage(new Page<FeedbackVO>(request, response),
                feedback);
        model.addAttribute("page", page);
        model.addAttribute("feedback", feedback);
        return "modules/business/feedback/feedbackList";
    }

    /**
     * 选择列表
     *
     * @return
     */
    @RequestMapping(value = "select")
    public String select(FeedbackVO feedback, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<FeedbackVO> page = feedbackService.findFeedbackByPage(new Page<FeedbackVO>(request, response, 10), feedback);
        model.addAttribute("page", page);
        model.addAttribute("feedback", feedback);
        return "modules/business/feedback/feedbackSelect";
    }

    /**
     * 用户添加更新表
     *
     * @param model
     * @return
     */
    @RequiresPermissions("business:feedback:view")
    @RequestMapping(value = "form")
    public String form(Model model, FeedbackVO feedback) {
        if (StringUtils.isNotEmpty(feedback.getId())) {
            FeedbackVO feedback1 = feedbackService.get(feedback.getId());
            List<FeedbackDetailVO> list = feedbackDetailService.findFeedbackDetailEntityByFeedbackId(feedback1.getId());
            model.addAttribute("feedback", feedback1);
            model.addAttribute("list", list);

        } else {
            model.addAttribute("feedback", feedback);
        }
        return "modules/business/feedback/feedbackForm";
    }

    /**
     * 讲问题分配给指定教师去回答
     * @param model
     * @param feedback
     * @return
     */
    @RequiresPermissions("business:feedback:view")
    @RequestMapping(value = "allot")
    public String allot(Model model, FeedbackVO feedback) {
        if (StringUtils.isNotEmpty(feedback.getId())) {
            feedback = feedbackService.get(feedback.getId());
        }
        model.addAttribute("feedback", feedback);
        return "modules/business/feedback/feedbackAllot";
    }

    @RequiresPermissions("business:feedback:edit")
    @RequestMapping(value = "allotsave")
    public String allotsave(FeedbackVO feedback, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, feedback)) {
            return form(model, feedback);
        }
        feedbackService.allotsave(feedback);
        addMessage(redirectAttributes, "保存成功");
        return "redirect:" + GlobalSetting.getAdminPath()+ "/business/feedback/?category=1";
    }
    /**
     * 添加或修改提交
     *
     * @param feedback
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("business:feedback:edit")
    @RequestMapping(value = "save")
    public String save(FeedbackVO feedback, Model model,
                       RedirectAttributes redirectAttributes) {// TODO @Valid 添加后端校验
        if (!beanValidator(model, feedback)) {
            return form(model, feedback);
        }
        feedbackService.update(feedback);
        addMessage(redirectAttributes, "保存成功");
        return "redirect:" + GlobalSetting.getAdminPath()
                + "/business/feedback/?category=1";
    }

    /**
     * 删除操作
     *
     * @return
     */
    @RequestMapping("delete")
    @RequiresPermissions("business:feedback:edit")
    public String delete(String id, RedirectAttributes redirectAttributes) {
        feedbackService.delete(id);
        addMessage(redirectAttributes, "删除成功");
        return "redirect:" + GlobalSetting.getAdminPath() + "/business/feedback/";
    }

    @RequiresPermissions("business:feedback:deal")
    @RequestMapping(value = "saveDeal")
    public String saveDeal(FeedbackVO feedback, RedirectAttributes redirectAttributes){
        FeedbackDetailVO feedbackDetailVO=new FeedbackDetailVO();
        if (StringUtils.isNotBlank(feedback.getResult())){
            feedbackDetailVO.setContent(feedback.getResult());
            feedbackDetailVO.setFeedbackId(feedback.getId());
            feedbackDetailService.saveDeal(feedbackDetailVO);
            addMessage(redirectAttributes,"回复成功");
        }
        return "redirect:" + GlobalSetting.getAdminPath() + "/business/feedback/deal?id="+feedback.getId();
    }

    /**
     * 教师反馈处理
     * @param model
     * @param feedback
     * @return
     */
    @RequiresPermissions("business:feedback:deal")
    @RequestMapping(value = "deal")
    public String deal(Model model, FeedbackVO feedback) {
        List<DealVo> list=new ArrayList<DealVo>();
        if (StringUtils.isNotEmpty(feedback.getId())) {
            feedback = feedbackService.get(feedback.getId());
            List<FeedbackDetailVO> FDlist = feedbackDetailService.findFeedbackDetailEntityByFeedbackId(feedback.getId());
            for (FeedbackDetailVO FDVo : FDlist) {
                DealVo dealVo=new DealVo();
                String content = FDVo.getContent();
                System.out.print(content);
                List<String> imgList = RegexUtils.match(content, "img", null, false);
                List<String> videoList = RegexUtils.match(content, "video", null, false);
                List<Media> medias = new ArrayList<Media>();
                for (String img : imgList) {
                    Media media = new Media();
                    List<String> img1 = RegexUtils.match(img, "img", "src", false);
                    String noimgUrl = img1.get(0); //图片路径
                   if (noimgUrl.endsWith("/")){
                       noimgUrl = noimgUrl.substring(0, noimgUrl.length() - 1);
                   }
                    media.setType("0");
                    media.setUrl(noimgUrl);
                    medias.add(media);
                }
                for (String video : videoList) {
                    Media media = new Media();
                    List<String> video1 = RegexUtils.match(video, "video", "src", false);
                    String novideoUrl = video1.get(0);//视频路径
                    novideoUrl=novideoUrl.substring(0,novideoUrl.length() - 1);
                    media.setType("1");
                    media.setUrl(novideoUrl);
                    medias.add(media);
                }
                String reg1 = "<[^>]*>";//去除所有html标签
                content = content.replaceAll(reg1, "");
                dealVo.setList(medias);
                dealVo.setContent(content);
                dealVo.setTime(FDVo.getCreateDate());
                if (FDVo.getReplyTeacher()!=null){
                    dealVo.setName(FDVo.getReplyTeacher().getName());
                    dealVo.setPortrait(FDVo.getReplyTeacher().getPortrait()==null?"http://data.fanrenqiji.com/upload/avtar0.jpg":FDVo.getReplyTeacher().getPortrait());
                }else if (FDVo.getParent()!=null){
                    dealVo.setName(FDVo.getParent().getName());
                    dealVo.setPortrait(FDVo.getParent().getPortrait()==null?"http://data.fanrenqiji.com/upload/avtar0.jpg":FDVo.getParent().getPortrait());
                }else{
                    dealVo.setName(FDVo.getCreateBy());
                    dealVo.setPortrait("http://data.fanrenqiji.com/upload/avtar0.jpg");
                }
                list.add(dealVo);
            }
        }
        model.addAttribute("list",list);
        return "modules/business/feedback/feedbackDeal";
    }

    /**
     * 将feedback中的数据封到DealVo 中
     * @param feedback
     * @return
     */
   /* public DealVo toDealVo(FeedbackVO feedback){
        DealVo dealVo=new DealVo();
        if (feedback!=null && feedback.getToTeacher()!=null){
            dealVo.setName(feedback.getToTeacher().getName());
            dealVo.setPortrait(feedback.getToTeacher().getPortrait().equals("")?"http://data.fanrenqiji.com/upload/avtar0.jpg":feedback.getToTeacher().getPortrait());
            dealVo.setTime(feedback.getSubmitTime());
            dealVo.setContent(feedback.getContent());
        }
        List<Media> medialist = new ArrayList<Media>();
        if (StringUtils.isNotBlank(feedback.getResources())){
            List<Map<String, Object>> maps = JSONHelper.toList(feedback.getResources());
            for(int i=0;i<maps.size();i++){
                Map<String, Object> map = maps.get(i);
                Media media=new Media();
                for(String key : map.keySet()){
                    media.setType(key);
                    String value = (String) map.get(key);
                    media.setUrl(value);
                }
                medialist.add(media);
            }
        }
        dealVo.setList(medialist);
        return dealVo;
    }*/

}